<?php
/**
 * Cities Cutover Interface
 */

// Load Custover Information
use Fox\Ddic\DataElement\Formater\Alpha;
use Fox\Common\Localization\City;
use Fox\Html\Input;
use Fox\Html\Screen;

set_time_limit(9500);
	
$screen = new Screen("cutover","execute");
$block = new Block("bCutover","Selection Criteria");
$block->add(new TextArea(array("comments","cityname")));
$block->add(new CheckBox("commit"));
$block->add(new Input("dbcnt",true,100));
$screen->add($block);
if($screen->posted())
{
	$inputs = $screen->get();
	$created = $loaded = 0;
	if(!Xview::instance()->errors())
	{
		$query = \Fox\Dao::infos(City::className())->handle()->createQueryBuilder();
		$query->select('t.*')
				->from('city_cutover','t')
				->leftJoin('t','cities','c','t.postal_code = c.postal_code AND t.isocode = c.iso_code')
				->orderBY('t.iso_code')
				->setMaxResults($inputs['dbcnt']);
		$fragments[] = $block->item('cityname')->fragments();
		$fragments[] = new Fox\Dao\SqlFragment("cityname != '' AND c.postal_code IS NULL AND c.iso_code IS NULL");
		$fragment = Fox\Dao\SqlFragment::combine($fragments);
		$result = $fragment->pushIn($query)->execute()->fetchAll(PDO::FETCH_ASSOC);
		$commit = $inputs['commit'];
		$loaded = count($result);
		foreach($result as $data)
		{
			$keyname = Fox\Utilities::cleanup($data['cityname']);
			$fields['fullname'] = $data['cityname'];
			$fields['keyname'] = $keyname;
			$fields['postal_code'] = sprintf("%05s",$data['postal_code']);
			$fields['iso_code'] = $data['isocode'];
			$fields['surface'] = $data['surface'];
			$fields['inhabitants'] = $data['population'];
			
			try {
				$city = new City();
				$city->setFields($fields);
				if($commit)
				{
					$city->create();
				}
				push_msg("S","City {$data['cityname']} has been created");
				$created++;
			}
			catch (Fox\Object\Exception\Save $e)
			{
				push_msg("E",$e->getMessage());
			}
			unset($fields);
		}
		
	}
	push_msg("I","Entries loaded : $loaded");
	push_msg("I","Entries created : $created");
	
}
echo $screen->display();